<?php

namespace App\Http\Controllers\Back;

use App\Models\Back\Category;
use App\Tool\Tool;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CategoryController extends Controller
{
	/*
	 * 设置
	 * get请求显示页面
	 * post请求添加品牌或修改品牌信息
	 */
	public function set (Request $request, $id = 0)
	{
		//实例化模型
		$Model = new Category();
		if ($request->isMethod('post')) {
			$data = $request->all();
			//表单验证
			$Model->setValidator($data);

			//上传image
			if ($request->hasFile('image') && $request->file('image')->isValid()) {
				$imagePath = $Model->categoryUpload($request);

				if ($imagePath) {
					//生成缩略图
					$Model->categoryThumb($imagePath);
					$data['image'] = $imagePath;
				}
			}

			//更新数据库
			$res = $Model->set($data);

			if ($res) {
				return redirect('/admin/category/list');
			} else {
				return back()->withInput();
			}
		} else {
			if ($id) {
				//获取单条品牌信息
				$category = Category::find($id);
				//获取无限级后的分类
				$handleCollection = $Model->getCategoryTree();
				$assign['category'] = $category;
				$assign['handleCollection'] = $handleCollection;
				return view('back.category.set', $assign);
			} else {
				//获取无限级后的分类
				$handleCollection = $Model->getCategoryTree();
				$assign['handleCollection'] = $handleCollection;
				return view('back.category.set', $assign);
			}
		}
	}



	/*
	 * 展示品牌列表
	 * post提交过来为删除操作
	 */
	public function show (Request $request, $field = 'id', $order = 'asc')
	{
		$Model = new Category();
		if ($request->isMethod('post')) {
			//验证
			$Model->deleteValidator($request->all());

			//删除
			$Model->deleteCategory($request->input('selected'));
			return back();
		} else {
			//取排序后的结果集
			$Collection = $Model->categoryOrder($field, $order);
			$handleCollection = Tool::tree($Collection);
			//处理页面class和url问题
			$list = Tool::sortClass($field, $order);
			$list['categoryCollection'] = $handleCollection;
			return view('back.category.list', $list);
		}
	}
}
